﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Kingdee.BOS.Contracts.Report;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.Report;
using Kingdee.BOS;
using Kingdee.BOS.Core.List;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.App;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using System.ComponentModel;

namespace PoorderBillFXHZ
{
    [Description("采购统计分析汇总服务插件")]
    [Kingdee.BOS.Util.HotUpdate]
    public class HZFService : SysReportBaseService
    {
        #region 临时表定义
        //临时表集合
        private List<string> tempTable = new List<string>();
        //接存储过程的临时表
        private string T_Temp_First = string.Empty;
        //最终数据表
        private string T_Temp_Last = string.Empty;
        //自己创建的临时表的SQL语句 List
        List<SqlObject> listTableSqlObj = new List<SqlObject>();

        #endregion

        #region 报表加载初始化
        public override void Initialize()
        {
            base.Initialize();
            this.ReportProperty.ReportType = ReportType.REPORTTYPE_NORMAL;
            this.ReportProperty.ReportName = new LocaleValue("采购统计分析汇总查询", this.Context.UserLocale.LCID);
            this.ReportProperty.SimpleAllCols = true;
            this.ReportProperty.IsGroupSummary = true; // 支持分组汇总

            //this.ReportProperty.DecimalControlFieldList = new List<DecimalControlField>();
            //// 标示famount用famount_decimal做精度格式化
            //this.ReportProperty.DecimalControlFieldList.Add(new DecimalControlField() { ByDecimalControlFieldName = "famount", DecimalControlFieldName = "famount_decimal" });

        }
        #endregion

        public override Kingdee.BOS.Core.Report.ReportTitles GetReportTitles(Kingdee.BOS.Core.Report.IRptParams filter)
        {
            string FORGName, FSYear, FEYear;

            ReportTitles titles = new ReportTitles();
            DynamicObject dyFilter = filter.FilterParameter.CustomFilter;

            DynamicObject FORG = dyFilter["FSUBORGID"] as DynamicObject;
            FORGName = Convert.ToString(FORG["Name"]);

            FSYear = Convert.ToString(dyFilter["FSYear"]);
            FEYear = Convert.ToString(dyFilter["FEYear"]);

            titles.AddTitle("FSUBORGID", FORGName);
            titles.AddTitle("FSYear", FSYear);
            titles.AddTitle("FEYear", FEYear);

            return titles;
        }
        public override Kingdee.BOS.Core.Report.ReportHeader GetReportHeaders(Kingdee.BOS.Core.Report.IRptParams filter)
        {
            ReportHeader header = new ReportHeader();


            ListHeader CG = header.AddChild();
            CG.Caption = new LocaleValue("采购", this.Context.UserLocale.LCID);
            CG.AddChild("RowNumberA", new LocaleValue("序号", this.Context.UserLocale.LCID), SqlStorageType.SqlBigInt).Width=50;
            CG.AddChild("FSupNameA", new LocaleValue("客户", this.Context.UserLocale.LCID), SqlStorageType.Sqlvarchar).Width=250;
            CG.AddChild("FSJCG", new LocaleValue("采购金额", this.Context.UserLocale.LCID), SqlStorageType.SqlDecimal).Width =150;

            ListHeader CGYF = header.AddChild();
            CGYF.Caption = new LocaleValue("采购应付", this.Context.UserLocale.LCID);
            CGYF.AddChild("RowNumberB", new LocaleValue("序号", this.Context.UserLocale.LCID), SqlStorageType.SqlBigInt).Width = 50;
            CGYF.AddChild("FSupNameB", new LocaleValue("客户", this.Context.UserLocale.LCID), SqlStorageType.Sqlvarchar).Width = 250;
            CGYF.AddChild("FSJFJAmount", new LocaleValue("采购应付金额", this.Context.UserLocale.LCID), SqlStorageType.SqlDecimal).Width = 150;



            return header;

        }

        public override void BuilderReportSqlAndTempTable(Kingdee.BOS.Core.Report.IRptParams filter, string tableName)
        {
            DynamicObject dyFilter = filter.FilterParameter.CustomFilter;
            //创建所需临时表
            CreatBillDataFirstTempTable(filter);
            T_Temp_Last = tableName;  //获得最终返回数据临时表名
            //执行建表语句
            DBUtils.ExecuteBatch(this.Context, listTableSqlObj);
            listTableSqlObj.Clear();
            //把存储过程里的数据插入临时表里
            InsertFirstTempTable(this.Context, filter);

            //最后再把数导入到最后的返回表里
            string sSQL = @"/*dialect*/ select a.* , {0}  into {1} from " + this.T_Temp_First + " a " + " order by RowNumberA";
            KSQL_SEQ = string.Format(KSQL_SEQ, "RowNumberA");
            sSQL = string.Format(sSQL, this.KSQL_SEQ, tableName);
            DBUtils.Execute(this.Context, sSQL);
            this.DeleteTempTable();   //删除临时表
        }


        /// <summary>
        /// 创建临时表用来接后台存储过程传过来的数据，因为有动态列所以还需要传一下过滤条件
        /// </summary>
        private void CreatBillDataFirstTempTable(IRptParams filter)
        {
            StringBuilder sbSql = new StringBuilder();
            IDBService service = ServiceHelper.GetService<IDBService>();
            T_Temp_First = service.CreateTemporaryTableName(this.Context);
            sbSql.AppendFormat(@"CREATE TABLE {0}
                                   (RowNumberA int ,
                                    FSupNameA nvarchar(500) default '',
                                    FSJCG decimal(19,2) default 0,
                                    RowNumberB int,
                                    FSupNameB nvarchar(500) default '',
                                    FSJFJAmount decimal(19,2) default 0
                                     ) ", T_Temp_First);
            listTableSqlObj.Add(new SqlObject(sbSql.ToString(), new List<SqlParam>()));
            //记录自己创建的临时表
            tempTable.Add(T_Temp_First);
            sbSql.Clear();
        }


        /// <summary>
        /// 根据过滤条件获得执行存储过程的参数
        /// </summary>
        private string GetSpParams(IRptParams filter)
        {
            string FSUBORGID, FSYear, FEYear, FText;

            ReportTitles titles = new ReportTitles();
            DynamicObject dyFilter = filter.FilterParameter.CustomFilter;

            DynamicObject FORG = dyFilter["FSUBORGID"] as DynamicObject;
            FSUBORGID = Convert.ToString(FORG["id"]);


            FSYear = Convert.ToString(dyFilter["FSYear"]);

            FEYear = Convert.ToString(dyFilter["FEYear"]);

            FText = Convert.ToString(dyFilter["FText"]);


            return "'" + FSYear + "','" + FEYear + "',  '" + FSUBORGID + "','"+ FText + "'";
        }

        /// <summary>
        /// 填充数据到最终的临时表里
        /// </summary>
        private void InsertFirstTempTable(Context ctx, IRptParams filter)
        {
            StringBuilder sql = new StringBuilder();

            //这个时候还没有返回表呢,先创建一下吧 

            sql.Append("/*dialect*/ INSERT INTO " + T_Temp_First);
            sql.Append("  exec BT_POOrTJHZ " + GetSpParams(filter));

            DBUtils.Execute(ctx, sql.ToString());
            sql.Clear();
        }

        /// <summary>
        /// 删除临时表操作
        /// </summary>
        public void DeleteTempTable()
        {
            IDBService service = Kingdee.BOS.App.ServiceHelper.GetService<IDBService>();
            if (this.tempTable.Count > 0)
            {
                //删除临时表
                service.DeleteTemporaryTableName(this.Context, this.tempTable.ToArray());
                this.tempTable.Clear();
            }
        }

        /// <summary>
        /// 设置报表合计列
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        public override List<SummaryField> GetSummaryColumnInfo(IRptParams filter)
        {
            var result = base.GetSummaryColumnInfo(filter);
            result.Add(new SummaryField("FSJCG", Kingdee.BOS.Core.Enums.BOSEnums.Enu_SummaryType.SUM));
            result.Add(new SummaryField("FSJFJAmount", Kingdee.BOS.Core.Enums.BOSEnums.Enu_SummaryType.SUM));

            return result;
        }
    }
}
